<template>
  <div class="tabbar">
    <ul class="ul">
      <router-link
        tag="li"
        v-for="(tabbar, index) in tabbars"
        @click.native="changeTab(index)"
        :key="tabbar.meta.titleTab"
        :to="`/${tabbar.meta.path}`"
      >
        <div class="icon_tab">
          <img v-show="active == index" :src="tabbar.meta.active" alt="" />
          <img v-show="active != index" :src="tabbar.meta.icon" alt="" />
        </div>
        <span>{{ tabbar.meta.titleTab }}</span>
      </router-link>
    </ul>
  </div>
</template>

<script>
import routes from '@/router/router'
import { mapMutations } from 'vuex'
export default {
  name: 'tabbar',
  data() {
    return {
      active: 0,
    }
  },
  watch: {
    $route: 'getPath',
  },
  created() {
    this.active = this.$store.state.active
    this.tabbars = routes.filter((item) => {
      if (item.meta && item.meta.isTab) {
        return item.meta
      }
    })
  },
  methods: {
    ...mapMutations(['SAVE_TABBAR_STATUS']),
    changeTab(e) {
      this.SAVE_TABBAR_STATUS(e)
      this.active = e
    },
    getPath() {
      let { name = '' } = this.$route
      let found = false
      this.tabbars.forEach((item) => {
        if (item.name === name) {
          this.active = item.meta.activeIndex
          found = true
        }
      })
      // 如果没有找到匹配的路由，保持当前active状态
      if (!found) {
        // 可以设置默认值，或者保持当前状态
        this.active = this.$store.state.active || 0
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.router-link-exact-active,
.router-link-active {
  color: #273de3 !important;
}
.tabbar {
  width: 100%;
  height: 60px;
  .ul {
    width: 100%;
    height: 100%;
    padding: 0;
    box-sizing: border-box;
    border-top: 1px solid rgba(94, 94, 94, 0.1);
    color: rgba(94, 94, 94, 0.3);
    list-style: none;
    margin: 0px;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    li {
      text-align: center;
      display: flex;
      color: #abb1d8;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      position: relative;
      .icon_tab {
        width: 22px;
        height: 23px;
      }
      span {
        font-size: 14px;
        // margin-top: 5px;
      }
      .totalNum {
        position: absolute;
        right: 10px;
        top: -5px;
        color: #fff;
        font-size: 14px;
        width: 20px;
        height: 20px;
        text-align: center;
        line-height: 20px;
        border-radius: 50%;
      }
    }
  }
}
</style>
